package offer.linkedList;

/**
 * @author DengYuan2
 * @create 2021-03-07 9:32
 */
public class NC50 {
    public static void main(String[] args) {
        NC50 n = new NC50();
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next=n5;
        ListNode res = n.reverseKGroup(n1, 3);
        System.out.println(res);
    }

    /**
     * @param head
     * @param k
     * @return
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        if (head==null || head.next==null || k==1){
            return head;
        }
        ListNode cur=head;
        int count=0;
        while (cur!=null){
            count++;
            cur=cur.next;
        }
        cur=head;
        ListNode res=new ListNode(-1);
        res.next=head;
        ListNode pre=res;
        ListNode tmp=null;
        for (int i = 0; i < count / k; i++) {
            for (int j = 0; j < k - 1; j++) {
                tmp=cur.next;
                cur.next=tmp.next;
                tmp.next=pre.next;
                pre.next=tmp;
            }
            pre=cur;
            cur=cur.next;
        }
        return res.next;
    }

}
